#序列号生成器
from fastapi import FastAPI
import uvicorn
from starlette.responses import HTMLResponse
from starlette.staticfiles import StaticFiles
from tinydb import TinyDB, Query
import os
import time
location='static'

app = FastAPI()


@app.get("/")
async def root(q: str=None,action:str=None):
    content='''
    <form action="">
    <br>ST Wafer 批次号生成器</br>
    <br><input type="text" name="q" value="">
    <input type="submit" name="action" value="搜索">
    <input type="submit" name="action" value="新建">
    </form>
    <span id='copy'>{}</span>
    '''
    test='''

<button id='btn'>复制</button>

<script type="text/javascript">
    function copyText()
    {
        var Url2=document.getElementById("copy").innerText;
        var oInput = document.createElement('input');
        oInput.value = Url2;
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象
        document.execCommand("Copy"); // 执行浏览器复制命令
        oInput.className = 'oInput';
        oInput.style.display='none';
        alert('复制成功');
    }
    document.getElementById('btn').onclick = function() {
        copyText()
    }
</script>


'''
    if action=="新建":
        
        if q:
            if len(q)==7:
                while os.path.exists('lock'):
                    #print('true')
                    time.sleep(1)

                db = TinyDB('db1.json')
                #Fruit = Query()
                x=db.search(Query().type == q)
                os.mkdir('lock')
                if x:
                    #print('有结果')
                    old=int(x[-1]['id'][-2:])+100
                    new=q+'G'+str(old+1)[-2:]
                    #print(new)
                    
                    db.update({'id': new}, Query().type == q)
                else:
                    #print('x不存在')
                    new=q+'G'+"00"
                    db.insert({'type': q, 'id': q+"G"+"00"})
                #print('x',x)
                db.close()
                os.rmdir('lock')
                return HTMLResponse(content=content.format(new)+test)
            else:
                return HTMLResponse(content=content.format(q+'长度非7位'))
        else:
            return HTMLResponse(content=content.format("")+test)
    elif action=="搜索":
        if q:

            db = TinyDB('db1.json')
            #Fruit = Query()
            x=db.search(Query().type == q)
            if x:
                #print('有结果')
                old=db.search(Query().type == q)[-1]['id']
                
                #print(new)
                #db.update({'id': new}, Query().type == q)
            else:
               old=q+'不存在'
                #new=q+'G'+"00"
                #db.insert({'type': q, 'id': q+"G"+"00"})
            #print('x',x)
            db.close()
            return HTMLResponse(content=content.format(old))
        else:
            return HTMLResponse(content=content.format(""))
        
    else:
        return HTMLResponse(content=content.format(""))
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0",port=8080,log_level="info")
